package com.example.order.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.example.order.bean.Order;
import com.example.order.properties.OrderProperties;
import com.example.order.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RequestMapping("/api/order/")
@Slf4j
//配置自动刷新
//@RefreshScope
@RestController
public class OrderController {

    @Autowired
    OrderService orderService;
//    @Value("${order.timeout}")
//    String orderTimeout;
//    @Value("${order.auto-confirm}")
//    String orderAutoConfirm;
    @Autowired
    OrderProperties orderProperties;

    @GetMapping("/config")
    public String config(){
        return "order.timeout = "+ orderProperties.getTimeout() +
                "; order.auto-confirm = " + orderProperties.getAutoConfirm() +
                "; order.db-url=" + orderProperties.getDbUrl();
       // return "order.timeout = "+ orderTimeout +"; order.auto-confirm = " + orderAutoConfirm;
    }

    //创建订单

    @GetMapping("/create")
    public Order createOrder(@RequestParam("userId") Long userId,@RequestParam("productId") Long productId){
        return orderService.CreateOrder(productId, userId);
    }

    @GetMapping("/seckill")
    @SentinelResource(value = "seckill-order", fallback = "seckillFallback")
    public Order seckill(@RequestParam(value = "userId", required = false) Long userId,
                         @RequestParam(value = "productId", defaultValue = "1000")Long productId){
        Order order = orderService.CreateOrder(productId, userId);
        order.setId(Long.MAX_VALUE);
        //异常模拟
        int i = 10/0;
        return order;
    }

    public Order seckillFallback(Long userId, Long productId, Throwable exception){
        System.out.println("seckillFallback....");
        Order order = new Order();
        order.setId(productId);
        order.setUserId(userId);
        order.setAddress("异常信息"+ exception.getClass());
        return order;
    }

    @GetMapping("/writeDb")
    public String writeDb(){
        return "writeDb success....";
    }

    @GetMapping("/readDb")
    public String readDb() {
        log.info("readDb....");
        return  "readDb success....";
    }
}
